<template>
	<view class="container">
		<!-- 顶部导航栏 -->
		<view class="nav-bar">
			<uni-icons type="back" size="28" color="#fff" @click="goBack" />
			<text class="title">就近加油</text>
			<view class="right-icons">
			</view>
		</view>

		<!-- 搜索框 -->
		<view class="search-bar">
			<input class="search-input" placeholder="输入需要搜索的内容" @input="handleSearch" />
			<uni-icons type="search" size="22" color="#999" />
		</view>

		<!-- 油号选择 -->
		<view class="oil-type-list">
			<view v-for="item in oilTypes" :key="item" :class="['oil-type', selectedOil === item ? 'active' : '']"
				@click="selectOil(item)">
				{{ item }}
			</view>
		</view>

		<!-- 地图模式按钮 -->
		<view class="map-mode-btn" @click="toMapMode">
			地图模式
		</view>

		<!-- 加油站列表 -->
		<view class="station-list">
			<view class="station-card" v-for="(station, idx) in stations" :key="idx" @click="toDetails(station)">
				<view class="station-header">
					<text class="station-title">{{ station.name }}</text>
					<text class="station-distance">{{ station.distance }}km</text>
				</view>
				<view class="station-tags">
					<text class="tag">{{ selectedOil }}: ¥{{ getSelectedOilPrice(station.id) }}</text>
				</view>
				<view class="station-content">
					<image :src="station.img" class="station-img" mode="aspectFill" />
					<view class="station-info">
						<text class="station-time">营业时间：{{ station.week }}</text>
						<view class="station-bottom">
							<text class="station-address">{{ station.address }}</text>
							<image src="/static/plane.png" mode="aspectFill" />
						</view>
					</view>
				</view>
			</view>
		</view>
	</view>
</template>

<script>
	import request from '../../uitls/request';

	export default {
		data() {
			return {
				oilTypes: [],
				selectedOil: '',
				stations: [],
				currentLat: 0, // 当前纬度
				currentLng: 0,  // 当前经度
				gasTypeMap: {}, // 存储加油站和油价的映射关系
				gasTypeList: [], // 存储油品类型列表
				searchText: '', // 搜索文本
				allStations: [] // 存储所有加油站数据
			}
		},
		methods: {
			goBack() {
				uni.navigateBack();
			},
			selectOil(item) {
				this.selectedOil = item;
			},
			toMapMode() {
				uni.navigateTo({
					url: '/pages/nearby-gas/map-mode/map-mode'
				});
			},
			toDetails(station) {
				uni.navigateTo({
					url: '/pages/shopDetails/shopDetails?id=' + station.id + '&distance=' + station.distance
				})
			},
			 // 新增：经纬度距离计算函数（Haversine公式）
			    calculateDistance(lat1, lon1, lat2, lon2) {
			      const earthRadius = 6371; // 地球半径（公里）
			      const dLat = this.deg2rad(lat2 - lat1);
			      const dLon = this.deg2rad(lon2 - lon1);
			      
			      const a = 
			        Math.sin(dLat/2) * Math.sin(dLat/2) +
			        Math.cos(this.deg2rad(lat1)) * Math.cos(this.deg2rad(lat2)) *
			        Math.sin(dLon/2) * Math.sin(dLon/2);
			      
			      const c = 2 * Math.atan2(Math.sqrt(a), Math.sqrt(1-a));
			      const distance = earthRadius * c; // 公里
			      return Number(distance.toFixed(3)); // 保留3位小数
			    },
			
			    // 角度转弧度辅助函数
			    deg2rad(deg) {
			      return deg * (Math.PI / 180);
			    },

			getCurrentLocation() {
				uni.getLocation({
					type: 'wgs84',
					success: (res) => {
						console.log('当前位置的经纬度：', {
							latitude: res.latitude,
							longitude: res.longitude
						});
						this.currentLat = res.latitude;
						          this.currentLng = res.longitude;
						          this.loadStations(); // 获取位置后加载加油站数据
					},
					fail: (err) => {
						console.error('获取位置失败：', err);
					}
				});
			},
			// 新增：加载加油站数据（分离数据请求与处理逻辑）
			loadStations() {
				request({
					url: '/xsc/cheer/list',
					method: 'GET',
					success: (res) => {
						if (res.data.code === 200) {
							// 计算每个加油站的距离
							this.allStations = res.data.rows.map(station => ({
								...station,
								distance: this.calculateDistance(
									this.currentLat, 
									this.currentLng, 
									station.latitude, 
									station.logitude
								)
							}));
							this.filterStations(); // 初始化显示所有加油站
						}
					}
				});
			},
			// 搜索处理函数
			handleSearch(e) {
				this.searchText = e.detail.value;
				this.filterStations();
			},
			// 过滤加油站
			filterStations() {
				if (!this.searchText) {
					this.stations = this.allStations;
					return;
				}
				this.stations = this.allStations.filter(station => 
					station.name.toLowerCase().includes(this.searchText.toLowerCase())
				);
			},
			// 获取油品类型和价格关系
			loadGasTypeRelations() {
				request({
					url: '/xsc/gas_cheer_type/list2',
					method: 'GET',
					success: (res) => {
						if (res.data.code === 200) {
							// 处理数据，建立加油站ID和油品类型的映射关系
							this.gasTypeMap = {};
							res.data.rows.forEach(item => {
								if (!this.gasTypeMap[item.gasCheerId]) {
									this.gasTypeMap[item.gasCheerId] = {};
								}
								this.gasTypeMap[item.gasCheerId][item.gasTypeId] = item.price;
							});
						}
					}
				});
			},
			// 获取油品类型列表
			loadGasTypes() {
				request({
					url: '/xsc/gastype/list',
					method: 'GET',
					success: (res) => {
						if (res.data.code === 200) {
							this.gasTypeList = res.data.rows;
							this.oilTypes = res.data.rows.map(type => type.name);
							if (this.oilTypes.length > 0) {
								this.selectedOil = this.oilTypes[0];
							}
						}
					}
				});
			},
			// 获取选中油品类型的价格
			getSelectedOilPrice(stationId) {
				const selectedType = this.gasTypeList.find(type => type.name === this.selectedOil);
				if (selectedType && this.gasTypeMap[stationId]) {
					return this.gasTypeMap[stationId][selectedType.id] || '暂无价格';
				}
				return '暂无价格';
			}
		},
		onLoad() {
			// 获取当前位置
			this.getCurrentLocation();
			
			// 加载油品类型列表
			this.loadGasTypes();
			
			// 加载油品类型和价格关系
			this.loadGasTypeRelations();
		}
	}
</script>

<style scoped>
	.container {
		/* #ifdef MP-WEIXIN */
		margin-top: 70rpx;
		/* #endif */
		background: linear-gradient(180deg, #2e8bff, #3ca7fa);
		background-size: 100% 35%;
		background-repeat: no-repeat;
		min-height: 100vh;
	}

	.nav-bar {
		display: flex;
		align-items: center;
		justify-content: space-between;
		padding: 40rpx 24rpx 24rpx 24rpx;
	}

	.title {
		color: #fff;
		font-size: 40rpx;
	}

	.right-icons {
		display: flex;
		width: 28px;
	}

	.search-bar {
		display: flex;
		align-items: center;
		background: #fff;
		border-radius: 40rpx;
		margin: 24rpx;
		padding: 0 24rpx;
		height: 86rpx;
		width: 70%;
	}

	.search-input {
		flex: 1;
		border: none;
		outline: none;
		font-size: 30rpx;
		background: transparent;
	}

	.oil-type-list {
		display: flex;
		gap: 15rpx;
		margin: 0 24rpx 24rpx 24rpx;
		flex-wrap: nowrap;
		/* 不换行 */
		overflow-x: auto;
		/* 超出可以横向滚动 */
	}

	.oil-type {
		padding: 6rpx 30rpx;
		border-radius: 20rpx;
		background: transparent;
		color: white;
		font-size: 28rpx;
		border: 2rpx solid white;
	}

	.oil-type-list::-webkit-scrollbar {
		display: none;
	}

	.map-mode-btn {
		/* #ifdef MP-WEIXIN */
		margin-top: 80rpx;
		/* #endif */
		text-align: center;
		position: absolute;
		right: 30rpx;
		top: 125rpx;
		background: linear-gradient(135deg, #ff9800, #ff5722);
		color: #fff;
		width: 80rpx;
		height: 80rpx;
		border-radius: 50%;
		font-size: 28rpx;
		padding: 10rpx;
		font-weight: bold;
		box-shadow: 0 4rpx 16rpx rgba(255, 152, 0, 0.2);
	}

	.station-list {
		margin: 24rpx;
	}

	.station-card {
		background: #fff;
		border-radius: 24rpx;
		margin-bottom: 32rpx;
		padding: 28rpx;
		box-shadow: 0 4rpx 24rpx rgba(0, 0, 0, 0.04);
	}

	.station-header {
		display: flex;
		justify-content: space-between;
		align-items: center;
	}

	.station-title {
		font-size: 36rpx;
		font-weight: bold;
	}

	.station-distance {
		color: #1976d2;
		font-size: 28rpx;
	}

	.station-tags {
		margin: 22rpx 0;
	}

	.tag {
		background: #ffebee;
		color: #ff5722;
		border-radius: 16rpx;
		padding: 4rpx 16rpx;
		margin-right: 16rpx;
		font-size: 24rpx;
	}

	.station-content {
		display: flex;
		margin-top: 12rpx;
	}

	.station-img {
		width: 180rpx;
		height: 150rpx;
		border-radius: 16rpx;
		margin-right: 24rpx;
		object-fit: cover;
	}

	.station-info {
		display: flex;
		flex-direction: column;
		justify-content: space-between;
	}

	.station-time,
	.station-price {
		font-size: 28rpx;
		margin-bottom: 8rpx;
	}

	.station-price {
		color: #ff9f86;
	}

	.station-info image {
		width: 30rpx;
		height: 30rpx;
		margin-left: 10rpx;
	}

	.station-bottom {
		display: flex;
		align-items: center;
		gap: 8rpx;
	}
</style>